import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import TextArea from '@/components/TextArea';
import { useAppDispatch, useAppSelector } from '@/store';
import {
  getProfileAction,
  updatePhotoAction,
  updateProfileAction,
} from '@/store/action/user';
import { IProfile } from '@/store/reducer/user';
import { DatePicker, Dialog, List, Popup, Toast } from 'antd-mobile';
import { useEffect, useRef, useState } from 'react';
import styles from './index.module.scss';
import dayjs from 'dayjs';
import { useHistory } from 'react-router-dom';
import { removeAuth } from '@/utils/storage';

type EditType = 'photo' | 'gender' | 'intro' | 'name';

export default function ProfileEdit() {
  const dispatch = useAppDispatch();
  const history = useHistory();
  useEffect(() => {
    dispatch(getProfileAction());
  }, [dispatch]);

  const { profile } = useAppSelector((state) => state.user);
  const [visible, setVisible] = useState(false);
  const [rightVisible, setRightVisible] = useState(false);
  const [name, setName] = useState(profile.name);
  const [intro, setIntro] = useState(profile.intro);
  const [birthVisible, setBirthVisible] = useState(false);

  useEffect(() => {
    setName(profile.name);
    setIntro(profile.intro || '');
  }, [profile]);

  const [editType, setEditType] = useState('' as EditType);

  const iptRef = useRef<HTMLInputElement>(null);

  const handleClickPhoto = () => {
    iptRef.current?.click();
  };

  const handleRefresh = () => {
    Toast.show({ content: '更新成功', icon: 'success' });
    setVisible(false);
    setRightVisible(false);
    setBirthVisible(false);
    dispatch(getProfileAction());
  };

  const handleUpdatePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      await dispatch(updatePhotoAction(e.target.files[0]));
      handleRefresh();
    }
  };

  const handleUpdateProfile = async (data: Partial<IProfile>) => {
    await dispatch(updateProfileAction(data));
    handleRefresh();
  };

  const renderPhotoOrGender = () => {
    if (editType === 'photo') {
      return (
        <>
          <div className="list-item" onClick={handleClickPhoto}>
            拍照
          </div>
          <div className="list-item" onClick={handleClickPhoto}>
            本地选择
          </div>
          <div className="list-item" onClick={() => setVisible(false)}>
            取消
          </div>
        </>
      );
    }

    if (editType === 'gender') {
      return (
        <>
          <div className="list-item" onClick={() => handleUpdateProfile({ gender: 0 })}>
            男
          </div>
          <div className="list-item" onClick={() => handleUpdateProfile({ gender: 1 })}>
            女
          </div>
          <div className="list-item" onClick={() => setVisible(false)}>
            取消
          </div>
        </>
      );
    }
  };

  const handleBack = () => {
    setName(profile.name);
    setIntro(profile.intro);
    setRightVisible(false);
  };

  const renderNameOrIntro = () => {
    const params = {} as Partial<IProfile>;
    if (editType === 'intro') params.intro = intro;
    if (editType === 'name') params.name = name;

    return (
      <>
        <NavBar
          onBack={handleBack}
          right={
            <span className="submit-btn" onClick={() => handleUpdateProfile(params)}>
              提交
            </span>
          }
        >
          编辑{editType === 'intro' ? '简介' : '昵称'}
        </NavBar>
        <div className="edit-content">
          {editType === 'intro' ? (
            <TextArea value={intro} onChange={(e) => setIntro(e.target.value)} />
          ) : (
            <Input
              className="edit-input"
              autoFocus
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
          )}
        </div>
      </>
    );
  };

  const showPopup = (editType: EditType) => {
    setEditType(editType);
    if (editType === 'photo' || editType === 'gender') setVisible(true);
    if (editType === 'intro' || editType === 'name') setRightVisible(true);
  };

  const handleLoginOut = () => {
    Dialog.confirm({
      title: '温馨提示',
      content: '是否确认退出',
      onConfirm: () => {
        removeAuth();
        Toast.show({ content: '退出成功', icon: 'success' });

        history.push('/login');
      },
    });
  };

  return (
    <div className={styles.root}>
      <div className="content">
        <NavBar>个人资料</NavBar>

        <div className="wrapper">
          <List className="profile-list">
            <List.Item
              arrow
              extra={<img className="avatar" src={profile.photo} alt="" />}
              onClick={() => showPopup('photo')}
            >
              头像
            </List.Item>

            <List.Item arrow extra={profile.name} onClick={() => showPopup('name')}>
              昵称
            </List.Item>

            <List.Item
              arrow
              extra={<span className="intro">{profile.intro}</span>}
              onClick={() => showPopup('intro')}
            >
              简介
            </List.Item>

            <List.Item
              arrow
              extra={profile.gender ? '女' : '男'}
              onClick={() => showPopup('gender')}
            >
              性别
            </List.Item>
            <List.Item
              arrow
              extra={profile.birthday}
              onClick={() => setBirthVisible(true)}
            >
              生日
            </List.Item>
          </List>

          <input
            ref={iptRef}
            className="avatar-upload"
            type="file"
            onChange={handleUpdatePhoto}
          />
        </div>

        <div className="logout">
          <button className="btn" onClick={handleLoginOut}>
            退出登录
          </button>
        </div>
      </div>

      <Popup
        bodyClassName="popup-bottom-list"
        visible={visible}
        onMaskClick={() => setVisible(false)}
      >
        {renderPhotoOrGender()}
      </Popup>
      <Popup
        visible={rightVisible}
        position="right"
        bodyClassName="popup-right"
        destroyOnClose
      >
        {renderNameOrIntro()}
      </Popup>
      <DatePicker
        min={new Date('1900-01-01')}
        max={new Date()}
        value={new Date(profile.birthday)}
        title="选择生日"
        visible={birthVisible}
        onConfirm={(value) => {
          console.log('value.  ----->  ', dayjs(value).format('YYYY-MM-DD'));
          handleUpdateProfile({ birthday: dayjs(value).format('YYYY-MM-DD') });
        }}
        onClose={() => setBirthVisible(false)}
      />
    </div>
  );
}
